<template>
  <div class="operator">
    <span class="operator-label">{{ label }}</span>
    <div class="operator-tags">
      <el-tag size="small" :key="tag" v-for="tag in tags" closable :disable-transitions="false" @close="handleClose(tag)">
        {{ tag }}
      </el-tag>
      <el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue" ref="saveTagInput" @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm" @input="trim(true)"> </el-input>
      <el-button v-else class="button-new-tag" icon="el-icon-plus" @click="showInput"></el-button>
    </div>
  </div>
</template>
<script>
/** vue */
import { defineComponent, reactive, toRefs, nextTick, ref } from 'vue';
/** utils */
import { useReg } from 'pub-bbx-utils';
const { isEmail } = useReg();
import { t } from '@src/locales';
/** element-ui */
import { Message } from 'element-ui';
export default defineComponent({
  name: 'OperatorTags',
  props: {
    dynamicTags: {
      type: Array,
      default: () => [],
    },
    label:{
      type: String,
      default: ''
    }
  },
  setup(props) {
    const saveTagInput = ref();

    const state = reactive({
      inputVisible: false,
      inputValue: '',
      tags: props.dynamicTags,
    });
    function handleClose(tag) {
      state.tags.splice(state.tags.indexOf(tag), 1);
    }

    function showInput() {
      state.inputVisible = true;
      nextTick(() => {
        saveTagInput.value.$refs.input.focus();
      });
    }
    
    function trim( isAll = false) {
      let reg = isAll ? /\s/g : /(^\s+)|(\s+$)/g
			state.inputValue = state.inputValue.replace(reg,'')
		}

    function handleInputConfirm() {
      let inputValue = state.inputValue;
      if (inputValue) {
        if (isEmail(inputValue)) {
          state.tags.push(inputValue);
        } else {
          Message.warning(t('im.imChat.components.mailChat.text11'));
        }
      }
      state.inputVisible = false;
      state.inputValue = '';
    }

    return {
      saveTagInput,
      ...toRefs(state),
      handleClose,
      showInput,
      handleInputConfirm,
      trim,
    };
  },
});
</script>
<style lang="scss" scoped>
.operator {
  display: flex;
  padding: 6px 12px 2px;
  &-label {
    font-size: 12px;
    color: #595959;
    line-height: 24px;
    margin-right: 20px;
    flex-shrink: 0;
  }
}
.operator-tags {
  display: flex;
  flex-wrap: wrap;
}
.el-tag {
  margin-bottom: 3px;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 24px;
  line-height: 24px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
  ::v-deep .el-input__inner {
    height: 28px !important;
    line-height: 28px !important;
  }
}
</style>
